/*
 *  Copyright 2008-2010 www.jrails.org
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.rails.core.model.attribute;

import org.rails.core.model.ActiveRecord;
import org.rails.core.util.Utils;

public final class BooleanAttribute extends AttributeBase {

	private Boolean value = false;

	public BooleanAttribute(final ActiveRecord record,final String attriubte) {
		super(record, attriubte);
	}

	@Override
	public void validate() throws AttributeException {
		this.value = parse(inputValue);
		if (isEmpty(this.value))
			this.value = getDefaultValue();

		if (require && isEmpty(this.value)) {
			throwAttRequireError();
		}
		
		if (unique)
			checkUnique();
	}

	@Override
	public Boolean parse(Object arg) {
		if (isEmpty(arg))
			return null;
		else if (arg instanceof Boolean)
			return (Boolean)arg;
		else if (arg instanceof Number)			
			return ((Number)arg).intValue() >= 1;
		else if (arg instanceof String)
			return Boolean.parseBoolean(arg.toString().trim());
		else
			return false;
	}

	@Override
	public Boolean getDefaultValue() {
		if (containsKey(DEFAULT_KEY))
			return parse(get(DEFAULT_KEY));
		else
			return null;
	}

	@Override
	public Boolean getValue() {
		return value;
	}

	@Override
	public Object getMax() {
		return null;
	}

	@Override
	public Object getMin() {
		return null;
	}

	@Override
	public boolean isTrim() {
		return false;
	}

	@Override
	public String format(Object arg) {
		if(Utils.isEmpty(arg)){
			return null;
		}else{
			return arg.toString();
		}
	}

}
